package scigest.metadata;

/**
 * Managing available chains. By implementing "BeanFactoryAware" interface, 
 * we can have a reference to the "beanFactory", which is used to obtain a 
 * reference to the requested chain via "createChain()" method.
 * 
 * The "runChain()" method is the entry point, where we execute a chain by chain's 
 * name.
 * 
 * 
 *
 * @author Feiyi Wang
 *
 */

import org.apache.commons.chain.impl.ChainBase;
import org.apache.commons.chain.impl.ContextBase;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

import scigest.configuration.ScigestConfiguration;

public class ChainRunner implements BeanFactoryAware {

		private BeanFactory beanFactory;
		private ContextBase ctxBase;
		
		
		public void runChain( String chainName ) {
			
			// initialize context for the chain
			ctxBase = new ContextBase();
			
			try {
				createChain( chainName ).execute ( ctxBase );
			}
			catch ( Exception ex) {
				throw new RuntimeException(
						"Chain [" + chainName + "]: Execution failure", ex);
			}
		}

		public ContextBase getContextBase() {
			return ctxBase;
		}
		
		/**
		 * This is a required method for BeanFactoryAware interface
		 * 
		 */
		public void setBeanFactory ( BeanFactory beanFactory ) throws BeansException {
			this.beanFactory = beanFactory;
		}

		protected ChainBase createChain( String chainName ) {
			return (ChainBase) this.beanFactory.getBean(chainName);
		}

}
